<template>
  <div class="workflow-executor">
    <!-- 工作流信息 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <h3>{{ workflow.title }}</h3>
          <el-tag v-if="workflow.type">{{ workflow.type }}</el-tag>
        </div>
      </template>
      <p class="description">{{ workflow.description }}</p>
      <div v-if="workflow.samples?.length" class="samples">
        <h4>示例</h4>
        <div class="sample-images">
          <el-image
            v-for="(sample, index) in workflow.samples"
            :key="index"
            :src="sample"
            :preview-src-list="workflow.samples"
            fit="cover"
          />
        </div>
      </div>
    </el-card>

    <!-- 参数表单 -->
    <dynamic-workflow
      :template="template"
      @execute="handleExecute"
    />

    <!-- 执行历史 -->
    <el-card v-if="showHistory" class="history-card">
      <template #header>
        <div class="card-header">
          <span>执行历史</span>
          <el-button-group>
            <el-button size="small" @click="refreshHistory">刷新</el-button>
            <el-button size="small" @click="clearHistory">清空</el-button>
          </el-button-group>
        </div>
      </template>

      <el-table
        :data="history"
        style="width: 100%"
        v-loading="loadingHistory"
      >
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="{ row }">
            {{ row.endTime ? formatDate(row.endTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'completed'"
              size="small"
              @click="viewResult(row)"
            >
              查看结果
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!history.length" class="empty-history">
        <el-empty description="暂无执行记录" />
      </div>
    </el-card>

    <!-- 结果查看对话框 -->
    <el-dialog
      v-model="resultDialog.visible"
      title="执行结果"
      width="800px"
    >
      <div class="result-content">
        <div v-if="resultDialog.images?.length" class="result-images">
          <el-image
            v-for="(image, index) in resultDialog.images"
            :key="index"
            :src="image"
            :preview-src-list="resultDialog.images"
            fit="cover"
          />
        </div>
        <div v-else class="no-result">
          <el-empty description="暂无结果" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { format } from 'date-fns'
import { ElMessage } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import DynamicWorkflow from './DynamicWorkflow.vue'
import type { Workflow, WorkflowTemplate, ExecutionRecord } from '@/types/workflow'

const props = defineProps<{
  workflow: Workflow
  showHistory?: boolean
}>()

const workflowStore = useWorkflowStore()

// 工作流模板
const template = computed<WorkflowTemplate>(() => {
  try {
    return JSON.parse(props.workflow.template)
  } catch (error) {
    console.error('Failed to parse template:', error)
    return {
      version: '1.0.0',
      workflow: {},
      params: [],
      layout: {
        groups: []
      }
    }
  }
})

// 执行历史
const history = ref<ExecutionRecord[]>([])
const loadingHistory = ref(false)

// 结果对话框
const resultDialog = ref({
  visible: false,
  images: [] as string[]
})

// 获取执行历史
const getHistory = async () => {
  try {
    loadingHistory.value = true
    history.value = await workflowStore.getExecutionHistory(props.workflow.id)
  } catch (error) {
    console.error('Failed to get history:', error)
    ElMessage.error('获取执行历史失败')
  } finally {
    loadingHistory.value = false
  }
}

// 刷新历史
const refreshHistory = () => {
  getHistory()
}

// 清空历史
const clearHistory = () => {
  history.value = []
}

// 查看结果
const viewResult = (execution: ExecutionRecord) => {
  try {
    const result = JSON.parse(execution.result || '{}')
    resultDialog.value = {
      visible: true,
      images: result.images || []
    }
  } catch (error) {
    console.error('Failed to parse result:', error)
    ElMessage.error('解析结果失败')
  }
}

// 处理执行
const handleExecute = async (params: Record<string, any>) => {
  try {
    const result = await workflowStore.executeWorkflow(props.workflow.id, params)
    if (props.showHistory) {
      refreshHistory()
    }
    return result
  } catch (error) {
    throw error
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'failed':
      return 'danger'
    case 'running':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'completed':
      return '已完成'
    case 'failed':
      return '失败'
    case 'running':
      return '执行中'
    case 'pending':
      return '等待中'
    default:
      return status
  }
}

// 格式化日期
const formatDate = (date: string | Date) => {
  return format(new Date(date), 'yyyy-MM-dd HH:mm:ss')
}

// 初始化
if (props.showHistory) {
  getHistory()
}
</script>

<style scoped lang="scss">
.workflow-executor {
  .info-card {
    margin-bottom: 24px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
      }
    }

    .description {
      margin: 16px 0;
      color: #666;
    }

    .samples {
      h4 {
        margin: 16px 0;
      }

      .sample-images {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 16px;

        .el-image {
          width: 100%;
          height: 150px;
          border-radius: 4px;
          overflow: hidden;
        }
      }
    }
  }

  .history-card {
    margin-top: 24px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .empty-history {
      padding: 24px 0;
    }
  }

  .result-content {
    .result-images {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 16px;

      .el-image {
        width: 100%;
        height: 200px;
        border-radius: 4px;
        overflow: hidden;
      }
    }

    .no-result {
      padding: 24px 0;
    }
  }
}
</style> 